<?php
declare (strict_types=1);

namespace app\middleware;

use app\common\helper\JwtHelper;
use app\common\model\User;
use Closure;
use Exception;
use think\Request;
use think\Response;

class CarryLogin extends Base
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $authorization = getAuthorization();
        if ($authorization) {
            try {
                $middlewareKey = 'userId';
                $middlewareInfoKey = 'userInfo';
                $userId = JwtHelper::verify($authorization);
                if ($userId) {
                    $userInfo = app(User::class)->getUserInfo($userId);
                    if (!$userInfo || empty($userInfo['status'])) {
                        throw new Exception('用户状态异常');
                    }
                    $request->$middlewareKey = $userId;
                    $request->$middlewareInfoKey = $userInfo;
                }
            } catch (Exception $ex) {
                return $next($request);
            }
        }

        return $next($request);
    }
}
